package com.tianhui.consignortwofei.mvp.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.entity.PictureInfo;
import com.fgs.common.entity.UploadPictureInfo;
import com.fgs.common.pictureSelector.SelectPicture;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.uploadPicture.IUploadPicture;
import com.fgs.common.uploadPicture.UploadPicture;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.widget.SelectDialog;
import com.fgs.common.widget.itemView.ClickItemView;
import com.fgs.common.widget.itemView.InputItemView;
import com.google.gson.Gson;
import com.luck.picture.lib.entity.LocalMedia;

import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.Config;
import com.tianhui.consignortwofei.constant.PictureType;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.QuotationListBean;
import com.tianhui.consignortwofei.mvp.model.enty.DictionaryInfo;
import com.tianhui.consignortwofei.mvp.model.enty.EventQuotationPaiHaoBean;
import com.tianhui.consignortwofei.mvp.model.enty.QuoationPaiHaoBean;
import com.tianhui.consignortwofei.myview.QuotationSelectDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/4/28
 * @description
 **/
public class PaiHaoActivity extends BaseActivity {


    @BindView(R.id.civ_paihao)
    ClickItemView civ_paihao;
    @BindView(R.id.civ_liexing)
    ClickItemView civ_liexing;
    @BindView(R.id.civ_huanquan)
    ClickItemView civ_huanquan;

    @BindView(R.id.iiv_num)
    InputItemView iiv_num;
    @BindView(R.id.iiv_price)
    InputItemView iiv_price;
    @BindView(R.id.iiv_quyu)
    InputItemView iiv_quyu;
    @BindView(R.id.iiv_cangku)
    InputItemView iiv_cangku;
    @BindView(R.id.iiv_name)
    InputItemView iiv_name;
    @BindView(R.id.iiv_phone)
    InputItemView iiv_phone;
    @BindView(R.id.iiv_beizhu)
    InputItemView iiv_beizhu;


    @BindView(R.id.rv_shop_image)
    RecyclerView rv_shop_image;

    @BindView(R.id.tv_save_dangqian)
    TextView tv_save_dangqian;





    private OrderModel orderModel;
    private QuotationListBean.QuotationRecords.PlasticsQuotationListDTO quotationListDTO;


    private QuotationSelectDialog mPaiHaoDialog;
    private SelectDialog mLeiXingDialog;
    private SelectDialog mHuoQuanDialog;
    private int addType=EventQuotationPaiHaoBean.ADDPAIHAO;

    @Override
    public int getLayoutId() {
        return R.layout.activity_pai_hao;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {
        setTitle("添加");

        orderModel = new OrderModel();

        initImageSelect();

        Bundle bundle = getIntent().getExtras();
        if (null!=bundle) {//null!=quatationDetailItem&& !TextUtils.isEmpty(quatationDetailItem)
            String quatationDetailItem = bundle.getString("quatationDetailItem");
            Gson gson = new Gson();
            quotationListDTO = gson.fromJson(quatationDetailItem, QuotationListBean.QuotationRecords.PlasticsQuotationListDTO.class);
            addType=EventQuotationPaiHaoBean.CHANGEPAIHAO;
            initView();
//            tv_save_dangqian.setVisibility(View.VISIBLE);
        }else {
            addType=EventQuotationPaiHaoBean.ADDPAIHAO;
            quotationListDTO=new QuotationListBean.QuotationRecords.PlasticsQuotationListDTO();
//            tv_save_dangqian.setVisibility(View.GONE);
        }




    }

    private void initView() {
        civ_paihao.setContent(quotationListDTO.getMfrname()+"|"+quotationListDTO.getName()+"|"+quotationListDTO.getProducer());
        civ_liexing.setContent(quotationListDTO.getTypename());
        civ_huanquan.setContent(quotationListDTO.getOwnershipname());

        iiv_num.setContent(quotationListDTO.getNumber());
        iiv_price.setContent(quotationListDTO.getPrice());
        iiv_quyu.setContent(quotationListDTO.getSalesarea());
        iiv_cangku.setContent(quotationListDTO.getWarehouse());
        iiv_name.setContent(quotationListDTO.getContacts());
        iiv_phone.setContent(quotationListDTO.getPhone());
        iiv_beizhu.setContent(quotationListDTO.getRemarks());



        try {
            if (null!=quotationListDTO.getImgpicture()&&!TextUtils.isEmpty(quotationListDTO.getImgpicture())){
                mVehicleImageSelectPictureList.add(quotationListDTO.getImgpicture());
//                String s = Config.baseImageUrl + quotationListDTO.getImgpicture();
//                iiv_name.setContent(s);
                List<LocalMedia> selectList =new ArrayList<>();
                LocalMedia media=new LocalMedia();
                media.setFileName("internet");
                media.setPath(Config.baseImageUrl+quotationListDTO.getImgpicture());
                media.setCutPath(quotationListDTO.getPicture());
                selectList.add(media);
                mVehicleImageSelectPicture.setAdapterData(selectList);

            }



        }catch (Exception e){
            LogUtil.print(e.toString());
        }

    }

    @Override
    public BaseFragment createFragment()
    {
        return null;
    }






    @OnClick(R.id.tv_save)
    public void savePaiHao() {

        String paihao = civ_paihao.getContent();
        String liexing = civ_liexing.getContent();
        String huanquan = civ_huanquan.getContent();

//        if (TextUtils.isEmpty(paihao)||TextUtils.isEmpty(liexing)||TextUtils.isEmpty(huanquan)){
//            ToastUtil.showShortToast("牌号，报价类型，货权选择后才可保存");
//            return;
//        }

        String num = iiv_num.getContent();
        String price = iiv_price.getContent();
        String quyu = iiv_quyu.getContent();
        String cangku = iiv_cangku.getContent();
        String name = iiv_name.getContent();
        String phone = iiv_phone.getContent();
        String beizhu = iiv_beizhu.getContent();

//        if (TextUtils.isEmpty(beizhu)){
//            ToastUtil.showShortToast("批量保存备注不能为空");
//            return;
//        }


        quotationListDTO.setNumber(num);
        quotationListDTO.setPrice(price);
        quotationListDTO.setSalesarea(quyu);
        quotationListDTO.setWarehouse(cangku);
        quotationListDTO.setContacts(name);
        quotationListDTO.setPhone(phone);
        quotationListDTO.setRemarks(beizhu);

        if (0<mVehicleImageSelectPictureList.size()) {
            quotationListDTO.setPicture(mVehicleImageSelectPictureList.get(0));
        }


        EventBus.getDefault().post(new EventQuotationPaiHaoBean(addType,0,quotationListDTO));
        finish();
    }


    @OnClick(R.id.tv_save_dangqian)
    public void saveDangQian() {
        String paihao = civ_paihao.getContent();
        String liexing = civ_liexing.getContent();
        String huanquan = civ_huanquan.getContent();

//        if (TextUtils.isEmpty(paihao)||TextUtils.isEmpty(liexing)||TextUtils.isEmpty(huanquan)){
//            ToastUtil.showShortToast("牌号，报价类型，货权选择后才可保存");
//            return;
//        }

        String num = iiv_num.getContent();
        String price = iiv_price.getContent();
        String quyu = iiv_quyu.getContent();
        String cangku = iiv_cangku.getContent();
        String name = iiv_name.getContent();
        String phone = iiv_phone.getContent();
        String beizhu = iiv_beizhu.getContent();

        quotationListDTO.setNumber(num);
        quotationListDTO.setPrice(price);
        quotationListDTO.setSalesarea(quyu);
        quotationListDTO.setWarehouse(cangku);
        quotationListDTO.setContacts(name);
        quotationListDTO.setPhone(phone);
        quotationListDTO.setRemarks(beizhu);

        if (0<mVehicleImageSelectPictureList.size()) {
            quotationListDTO.setPicture(mVehicleImageSelectPictureList.get(0));
        }

//        EventBus.getDefault().post(new EventQuotationPaiHaoBean(addType,0,quotationListDTO));
//        finish();
        EventBus.getDefault().post(new EventQuotationPaiHaoBean(3,0,quotationListDTO));
        savePaiHaoDangQian();
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(QuoationPaiHaoBean iSelectViewItem) {
        civ_paihao.setContent(iSelectViewItem.getMfrname()+"|"+iSelectViewItem.getName()+"|"+iSelectViewItem.getProducer());
//                mGoodsInfo.goodstype = iSelectViewItem.getSelectItemTextValue();
        quotationListDTO.setMfrname(iSelectViewItem.getMfrname());
        quotationListDTO.setProducer(iSelectViewItem.getProducer());

        quotationListDTO.setName(iSelectViewItem.getName());
        quotationListDTO.setUserplasticsid(iSelectViewItem.getId());
        quotationListDTO.setMfr(iSelectViewItem.getMfr());
        quotationListDTO.setNametype(iSelectViewItem.getType());

    }

    @OnClick(R.id.civ_paihao)
    public void showPaiHaoType() {
//        if (mPaiHaoDialog == null) {
//            getPaiHaoType();
//        } else {
//            mPaiHaoDialog.show();
//        }
        openActivity(PaiHaoSelectActivity.class);
    }





    private void getPaiHaoType(List<QuoationPaiHaoBean> dictionaryInfoList) {
        mPaiHaoDialog = new QuotationSelectDialog<QuoationPaiHaoBean>(this);
        mPaiHaoDialog.setTitle("请选择牌号");
        mPaiHaoDialog.setList(dictionaryInfoList);
        mPaiHaoDialog.show();

        mPaiHaoDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<QuoationPaiHaoBean>() {
            @Override
            public void onItemClick(QuoationPaiHaoBean iSelectViewItem, int position) {
                civ_paihao.setContent(iSelectViewItem.getMfrname()+"|"+iSelectViewItem.getName()+"|"+iSelectViewItem.getProducer());
//                mGoodsInfo.goodstype = iSelectViewItem.getSelectItemTextValue();
                quotationListDTO.setMfrname(iSelectViewItem.getMfrname());
                quotationListDTO.setProducer(iSelectViewItem.getProducer());

                quotationListDTO.setName(iSelectViewItem.getName());
                quotationListDTO.setUserplasticsid(iSelectViewItem.getId());
                quotationListDTO.setMfr(iSelectViewItem.getMfr());

            }
        });
    }


    @OnClick(R.id.civ_liexing)
    public void showLeiXingType() {
        if (mLeiXingDialog == null) {
            getLeiXingType();
        } else {
            mLeiXingDialog.show();
        }

    }


    private void getLeiXingType(List<DictionaryInfo> dictionaryInfoList) {
        mLeiXingDialog = new SelectDialog<DictionaryInfo>(this);
        mLeiXingDialog.setTitle("请选报价类型");
        mLeiXingDialog.setList(dictionaryInfoList);
        mLeiXingDialog.show();

        mLeiXingDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<DictionaryInfo>() {
            @Override
            public void onItemClick(DictionaryInfo iSelectViewItem, int position) {
                civ_liexing.setContent(iSelectViewItem.name);
////                mGoodsInfo.goodstype = iSelectViewItem.getSelectItemTextValue();
                quotationListDTO.setTypename(iSelectViewItem.name);
                quotationListDTO.setType(iSelectViewItem.num);


            }
        });
    }


    @OnClick(R.id.civ_huanquan)
    public void showHuoQuanType() {
        if (mHuoQuanDialog == null) {
            getHuoQuanType();
        } else {
            mHuoQuanDialog.show();
        }

    }

    private void getHuoQuanType(List<DictionaryInfo> dictionaryInfoList) {
        mHuoQuanDialog = new SelectDialog<DictionaryInfo>(this);
        mHuoQuanDialog.setTitle("请选择货权");
        mHuoQuanDialog.setList(dictionaryInfoList);
        mHuoQuanDialog.show();

        mHuoQuanDialog.setOnSelectItemClickLister(new SelectDialog.OnSelectItemClickListener<DictionaryInfo>() {
            @Override
            public void onItemClick(DictionaryInfo iSelectViewItem, int position) {
                civ_huanquan.setContent(iSelectViewItem.name);
////                mGoodsInfo.goodstype = iSelectViewItem.getSelectItemTextValue();
                quotationListDTO.setOwnershipname(iSelectViewItem.name);
                quotationListDTO.setOwnership(iSelectViewItem.num);


            }
        });
    }



    private void getPaiHaoType() {
        Map<String, String> map = new HashMap<>();
//        map.put("pid", "13");
        orderModel.getPaiHaoType(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<QuoationPaiHaoBean>>>() {
            @Override
            public void onNext(CommonResponse<List<QuoationPaiHaoBean>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<QuoationPaiHaoBean> list = commonResponse.getData();
                        if (list != null && list.size() > 0) {
                            getPaiHaoType(list);
                        } else {
                            showToast("未获取到牌号信息");
                        }
                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });
    }


    private void getLeiXingType() {
        Map<String, String> map = new HashMap<>();
        map.put("pid", "13");
        orderModel.dictionaryModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DictionaryInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DictionaryInfo>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<DictionaryInfo> list = commonResponse.getData();
                        if (list != null && list.size() > 0) {
                            getLeiXingType(list);
                        } else {
                            showToast("未获取到发送对象信息");
                        }
                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });
    }


    private void getHuoQuanType() {
        Map<String, String> map = new HashMap<>();
        map.put("pid", "12");
        orderModel.dictionaryModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DictionaryInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DictionaryInfo>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        List<DictionaryInfo> list = commonResponse.getData();
                        if (list != null && list.size() > 0) {
                            getHuoQuanType(list);
                        } else {
                            showToast("未获取到发送对象信息");
                        }
                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });
    }


    private void savePaiHaoDangQian() {


        orderModel.savePaiHaoDangQian(this, quotationListDTO, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<List<DictionaryInfo>>>() {
            @Override
            public void onNext(CommonResponse<List<DictionaryInfo>> commonResponse) {
                if (!isFinishing() && !isDestroyed()) {
                    if (commonResponse.getCode() == 20000) {
                        EventBusManage.refreshBaoJiaList();
                       showToast("添加成功");
                       finish();
                    } else {
                        showToast(commonResponse.getMsg());
                    }
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {

                showToast(e.message);
            }
        });
    }





    //================图片
    private SelectPicture mVehicleImageSelectPicture;
    List<String> mVehicleImageSelectPictureList = new ArrayList<>();
    private void initImageSelect() {
        mVehicleImageSelectPicture = new SelectPicture();
        mVehicleImageSelectPicture.setMaxSelectNum(1);
        mVehicleImageSelectPicture.selectMultiPicture(this, new SelectPicture.OnSelectResultCallback() {
            @Override
            public void selectResultCallback(List<LocalMedia> selectList) {

                if (null != selectList && selectList.size() > 0) {

                    mVehicleImageSelectPictureList.clear();

                    int size = selectList.size();
                    String path = "";
                    for (int i = 0; i < size; i++) {//判断是不是网络图片
                        if ("internet".equals(selectList.get(i).getFileName())){
                            PictureInfo info=new PictureInfo();
//                            info.id=selectList.get(i).getPath();
                            info.id=selectList.get(i).getCutPath();
                            processPictureUploadResult(info,1);
                        }else {
                            path = selectList.get(i).getCompressPath();
                            requestPictureUpload(PictureType.TYPE_VEHICLE_IMAGE, path, selectList.get(i));
                        }
                    }
                }
            }

            @Override
            public void selectResultPath(String path) {

            }

            @Override
            public void deletePictureCallback(List<LocalMedia> selectList, int position) {
                int size = mVehicleImageSelectPictureList.size();
                LogUtil.print("position--" + position + "\n" + "size--" + size);
                if (position < size) {
                    mVehicleImageSelectPictureList.remove(position);
                }

            }
        }, getVehicleImageRecyclerView());
    }

    public RecyclerView getVehicleImageRecyclerView() {
        return rv_shop_image;
    }

    private void requestPictureUpload(int type, String path, LocalMedia localMedia) {
        if (TextUtils.isEmpty(path)) return;
//        //添加水印
//        Bitmap bitmap = ImageUtil.getBitmap(path);
        File file=new File(path);//ImageUtil.getFile(bitmap)
        uploadPicture(type, file, localMedia);
    }

    private void uploadPicture(int type, File file, LocalMedia localMedia) {
        UploadPictureInfo uploadPictureInfo = new UploadPictureInfo();
        uploadPictureInfo.file = file;
        uploadPictureInfo.pictureModule = "dispatchSource";
        new UploadPicture(new IUploadPicture.UploadPictureCallback() {
            @Override
            public void onSuccess(UploadPictureInfo uploadPictureInfo, PictureInfo pictureInfo) {
                processPictureUploadResult(pictureInfo, type);
            }

            @Override
            public void onFailed(UploadPictureInfo uploadPictureInfo) {
                removePicture(type, localMedia);
            }
        }).uploadPicture(this, uploadPictureInfo);

    }

    private void removePicture(int type, LocalMedia localMedia) {
//        if (type == PictureType.TYPE_INVOICES_IMAGE) {
//            mSelectPicture.removePicture(localMedia);
//        } else
//        if (type == PictureType.TYPE_VEHICLE_IMAGE) {
            mVehicleImageSelectPicture.removePicture(localMedia);
//        }
    }

    private void processPictureUploadResult(PictureInfo pictureInfo, int type) {
//        switch (type) {
//            case PictureType.TYPE_INVOICES_IMAGE:
//                mSelectPictureList.add(pictureInfo.id);
//                break;
//            case PictureType.TYPE_VEHICLE_IMAGE:
        mVehicleImageSelectPictureList.add(pictureInfo.id);
//        imageId = pictureInfo.imageId;
        quotationListDTO.setImgpicture(pictureInfo.realFileName);
//                break;
//        }
        LogUtil.print("pictureID---" + pictureInfo.id);
    }











}
